package com.jd.ty.web;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.jd.ty.pojo.Customer;
import com.jd.ty.pojo.CustomerAppreciationLog;
import com.jd.ty.pojo.CustomerCompany;
import com.jd.ty.pojo.CustomerOrder;
import com.jd.ty.pojo.Dictionary;
import com.jd.ty.pojo.Employee;
import com.jd.ty.pojo.ProjectAttrValue;
import com.jd.ty.pojo.ProjectAttribute;
import com.jd.ty.service.CustomerOrderService;
import com.jd.ty.service.DictionaryService;
import com.jd.ty.service.EmployeeService;
import com.jd.ty.service.ProjectService;
import com.jd.ty.util.Pager;
import com.jd.ty.web.constant.DictionaryCode;
import com.jd.ty.web.filter.CheckOrderFilter;
import com.jd.ty.web.filter.CustomerOrderFilter;
import com.opensymphony.xwork2.conversion.annotations.TypeConversion;
import com.ty.xsl.field.DataSheet;
import com.ty.xsl.field.ExcelField;
import com.ty.xsl.field.Sheet;
import com.ty.xsl.parserule.ParseRule;
import com.ty.xsl.parserule.PortraitRule;
import com.ty.xsl.reader.XSLReader;

public class CustomerOrderAction extends BaseAction {
	private String term;

	private CheckOrderFilter filters = new CheckOrderFilter();

	private String fileName;

	private InputStream fileStream;

	@Override
	public String execute() throws Exception {
		loadResources();
		return SUCCESS;
	}

	public String orderInfo() {
		if (id != null) {
			customerOrder = customerOrderService.get(id[0]);

			departments = dictionaryService.getList(DictionaryCode.DEPARTMENT);
			positions = dictionaryService
					.getList(DictionaryCode.CUSTOMER_TITLE);
			projectTypes = dictionaryService
					.getList(DictionaryCode.ORDER_PROJECT_TYPE);
			orderStatus = dictionaryService
					.getList(DictionaryCode.ORDER_STATUS);
			for (Dictionary type : projectTypes) {
				List<ProjectAttribute> attriList = projectService
						.getProjectAttrsByParentId(type.getDictionaryId());
				for (ProjectAttribute projectAttribute : attriList) {
					List<ProjectAttrValue> values = customerOrder
							.getProjectAttrValues();
					for (ProjectAttrValue value : values) {
						if (value.getProjectAttribute().getAttrId().equals(
								projectAttribute.getAttrId())) {
							projectAttribute.setValue(value);
						}
					}
				}
				projectSet.put(type.getDictionaryId(), attriList);
			}

			employees = employeeService.getList(null);
		} else {
			loadResources();
		}

		return SUCCESS;
	}

	public String getOrderList() {
		pager = getPagerObject();
		List<CustomerOrder> res = customerOrderService.getList(pager,
				getFilter().toHqlString(), getSortStr());
		pager.setDataRows(res);
		return SUCCESS;
	}

	public String getCompanyList() throws UnsupportedEncodingException {
		List<CustomerCompany> companies = customerOrderService
				.getCompanyList(URLDecoder.decode(term, "UTF-8"));
		List dataRows = new ArrayList();
		for (CustomerCompany company : companies) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", company.getCustCompanyId());
			map.put("label", company.getCustCompanyName());
			map.put("value", company.getCustCompanyName());
			map.put("company", company);
			dataRows.add(map);
		}
		pager = getPagerObject();
		pager.setDataRows(dataRows);
		return SUCCESS;
	}

	public String getCustomerList() throws UnsupportedEncodingException {
		List<Customer> customers = customerOrderService
				.getCustomerList(URLDecoder.decode(term, "UTF-8"));
		List dataRows = new ArrayList();
		for (Customer customer : customers) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", customer.getCustomerId());
			map.put("label", customer.getCustomerName());
			map.put("value", customer.getCustomerName());
			map.put("customer", customer);
			dataRows.add(map);
		}
		pager = getPagerObject();
		pager.setDataRows(dataRows);
		return SUCCESS;
	}

	public Pager getPager() {
		return pager;
	}

	public String deleteOrder() {
		customerOrderService.deleteOrder(id);
		return SUCCESS;
	}

	public String saveOrder() {
		customerOrder.setProjectAttrValues(buildAttrValues());
		if (customerOrder.getOrderId() != null) {
			customerOrderService.updateOrder(customerOrder);
		} else {
			customerOrderService.addOrder(customerOrder);
		}
		return SUCCESS;
	}

	public String check() {
		List<Map<String, Object>> query = null;
		if (fileName != null) {
			query = inport();
		} else {
			query = getFilterList();
		}
		if (query != null) {
			checkOrder(query);
		}
		return SUCCESS;
	}

	private List<Map<String, Object>> getFilterList() {
		List<Map<String, Object>> set = filters.toSet();
		if (set.size() == 0) {
			return null;
		}
		return set;
	}

	private void checkOrder(List<Map<String, Object>> set) {
		pager = getPagerObject();
		customerOrderService.checkList(set);
		pager.setDataRows(set);
	}

	private ExcelField createFiled(String name, int index) {
		ExcelField field = new ExcelField();
		field.setIndex(index);
		field.setBeginIndex(1);
		field.setName(name);
		return field;
	}

	private List<Map<String, Object>> inport() {
		ParseRule rule = new PortraitRule();
		List<ExcelField> fields = new ArrayList<ExcelField>();

		fields.add(createFiled(CheckOrderFilter.MAP_KEY_COMPANY_NAME, 1));
		//REMOVE AT 2012-04-11, FOR REQUIREMENT CHAGNE
//		fields.add(createFiled(CheckOrderFilter.MAP_KEY_CUSTOMER_POSITION, 2));
//		fields.add(createFiled(CheckOrderFilter.MAP_KEY_CUSTOMER_NAME, 3));
//		fields.add(createFiled(CheckOrderFilter.MAP_KEY_PROJECT_TYPE, 4));

		rule.setFields(fields);

		List<Sheet> sheets = new ArrayList<Sheet>();
		Sheet sheet = new Sheet();
		String sheetName = "订单";
		sheet.setName(sheetName);
		sheets.add(sheet);

		DataSheet dataSheet = XSLReader.importExcel(sheets, rule, fileName);
		List<Map<String, Object>> list = dataSheet.get(sheetName);

		File file = new File(fileName);
		file.delete();
		return list;
	}

	public String downloadTemplate() throws UnsupportedEncodingException {
		fileName = "订单导入模板";
		fileName = new String(fileName.getBytes(), "ISO8859-1");
		String filePath = "download/订单导入模板.xls";
		fileStream = ServletActionContext.getServletContext()
				.getResourceAsStream(filePath);
		return SUCCESS;
	}

	private CustomerOrderService customerOrderService;

	private DictionaryService dictionaryService;
	private ProjectService projectService;
	private CustomerOrderFilter filter;
	private Long[] id;

	private HashMap<Long, List> projectSet = new HashMap<Long, List>();

	private EmployeeService employeeService;
	private List<Employee> employees;
	private List<Customer> customers;

	private List<Dictionary> departments;
	private List<Dictionary> positions;

	private List<Dictionary> projectTypes;
	private List<Dictionary> orderStatus;

	private CustomerOrder customerOrder;
	private CustomerAppreciationLog log;

	private Map<Long, ProjectAttrValue> projectAttrValues = new HashMap<Long, ProjectAttrValue>();

	public CustomerOrder getCustomerOrder() {
		return customerOrder;
	}

	public Map<Long, ProjectAttrValue> getProjectAttrValues() {
		return projectAttrValues;
	}

	public void setProjectAttrValues(
			Map<Long, ProjectAttrValue> projectAttrValues) {
		this.projectAttrValues = projectAttrValues;
	}

	public void setCustomerOrder(CustomerOrder customerOrder) {
		this.customerOrder = customerOrder;
	}

	private void loadResources() {
		departments = dictionaryService.getList(DictionaryCode.DEPARTMENT);
		positions = dictionaryService.getList(DictionaryCode.CUSTOMER_TITLE);
		projectTypes = dictionaryService
				.getList(DictionaryCode.ORDER_PROJECT_TYPE);
		orderStatus = dictionaryService.getList(DictionaryCode.ORDER_STATUS);
		for (Dictionary type : projectTypes) {
			projectSet.put(type.getDictionaryId(), projectService
					.getProjectAttrsByParentId(type.getDictionaryId()));
		}

		employees = employeeService.getList(null);

	}

	private List<ProjectAttrValue> buildAttrValues() {
		List<ProjectAttrValue> values = new ArrayList<ProjectAttrValue>();
		for (Iterator<Long> iterator = projectAttrValues.keySet().iterator(); iterator
				.hasNext();) {
			Long id = iterator.next();
			ProjectAttrValue value = projectAttrValues.get(id);
			ProjectAttribute attr = projectService.get(id);
			value.setProjectAttribute(attr);
			values.add(value);
		}

		return values;
	}

	public List<Customer> getCustomers() {
		return customers;
	}

	public void setCustomers(List<Customer> customers) {
		this.customers = customers;
	}

	public void setFilter(CustomerOrderFilter filter) {
		this.filter = filter;
	}

	public CustomerOrderFilter getFilter() {
		if (filter == null) {
			filter = new CustomerOrderFilter();
		}

		return filter;
	}

	public Long[] getId() {
		return id;
	}

	@TypeConversion(converter = "com.jd.ty.web.util.String2LongArrayConverter")
	public void setId(Long[] id) {
		this.id = id;
	}

	public void setDictionaryService(DictionaryService dictionaryService) {
		this.dictionaryService = dictionaryService;
	}

	public CustomerOrderService getCustomerOrderService() {
		return customerOrderService;
	}

	public void setCustomerOrderService(
			CustomerOrderService customerOrderService) {
		this.customerOrderService = customerOrderService;
	}

	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

	public DictionaryService getDictionaryService() {
		return dictionaryService;
	}

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public List<Employee> getEmployees() {
		return employees;
	}

	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}

	public List<Dictionary> getProjectTypes() {
		return projectTypes;
	}

	public void setProjectTypes(List<Dictionary> projectTypes) {
		this.projectTypes = projectTypes;
	}

	public List<Dictionary> getDepartments() {
		return departments;
	}

	public void setDepartments(List<Dictionary> departments) {
		this.departments = departments;
	}

	public CustomerAppreciationLog getLog() {
		return log;
	}

	public void setLog(CustomerAppreciationLog log) {
		this.log = log;
	}

	public HashMap<Long, List> getProjectSet() {
		return projectSet;
	}

	public void setProjectSet(HashMap<Long, List> projectSet) {
		this.projectSet = projectSet;
	}

	public List<Dictionary> getOrderStatus() {
		return orderStatus;
	}

	public void setOrderStatus(List<Dictionary> orderStatus) {
		this.orderStatus = orderStatus;
	}

	public String getTerm() {
		return term;
	}

	public void setTerm(String term) {
		this.term = term;
	}

	public CheckOrderFilter getFilters() {
		return filters;
	}

	public void setFilters(CheckOrderFilter filters) {
		this.filters = filters;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getFileStream() {
		return fileStream;
	}

	public void setFileStream(InputStream fileStream) {
		this.fileStream = fileStream;
	}

	public List<Dictionary> getPositions() {
		return positions;
	}

	public void setPositions(List<Dictionary> positions) {
		this.positions = positions;
	}

}
